OBJ=obj
LIB=.
SRC=src
GEN=generated
BIN=bin
INCLUDE=-I ../../include -I .
LIBNAME=pizza
SRCNAME=pizzadll
BUILD=debug
MODULE=x

SRC_FILES=$(shell find $(SRC) -name "*.adb") $(shell find $(GEN) -name "*.adb")
EXT_OBJ=
EXT_LIBS=
EXT_OBJDIR=
GNAT=-gnat05 -g -P $(LIBNAME).gpr $(EXT_LIBS) -j3 -gnatf -gnata

all:
	@echo "Usage: "
	@echo "   make dll - builds dll"
	@echo "   make test - runs test"
	
test: dll $(BIN)/javada/x/PizzaTest.class
	java -cp "$(BIN)" javada.x.PizzaTest
	
$(BIN)/javada/x/PizzaTest.class: $(SRC)/javada/x/PizzaTest.java $(GEN)/javada/x/Pizza.java
	javac -g -cp "$(SRC);$(GEN)" -d $(BIN) `find $(GEN) -name *.java` `find $(SRC) -name *.java` 

dll: $(LIB)/$(LIBNAME).dll
	
$(GEN)/$(MODULE).ads: $(LIBNAME).idl
	javada -O $(GEN) -L $(LIBNAME) $(INCLUDE) -J javada $^
	
$(OBJ)/%.o: $(GEN)/%.adb
	@echo
	@echo Building $@
	@gnatmake -c $^ $(GNAT)

$(OBJ)/%.o: $(SRC)/%.adb
	@echo
	@echo Building $@
	@gnatmake -c $^ $(GNAT)
	
$(OBJ)/*.o:
	
$(LIB)/$(LIBNAME).dll : $(GEN)/$(MODULE).ads $(OBJ)/$(SRCNAME).ali $(OBJ)/*.o $(SRCNAME).def
	@echo
	@echo ">>>>> Building $@ <<<<<"
	gnatdll -n -k -g -d $@ -l $(SRCNAME).lst -e $(SRCNAME).def -v $(EXT_OBJ) -bargs \
		$(EXT_OBJDIR) -E -largs

$(SRCNAME).def: $(SRC_FILES) $(EXT_OBJ)
	@echo
	@echo ">>> Listing JNI methods for DLL to export <<<"
	@echo LIBRARY $(SRCNAME) > $@
	@echo EXPORTS >> $@
	@echo "  DllMain@12" >> $@
	@nm $(EXT_OBJ) $(subst \,/,$(subst .ali,.o,$(shell cat $(SRCNAME).lst))) \
		| grep "T _Java_" | sed 's/^.* T _/  /' | sort | uniq >> $@

$(OBJ)/$(SRCNAME).ali: $(SRC_FILES)
	@echo
	@echo ">>> Making list of objects for DLL <<<"
	gnatmake -c $(GNAT) $(SRCNAME)
	@gnatmake -c $(GNAT) $(SRCNAME) -v 2>&1 | grep 'being checked' |\
	sed 's/" being.*//' | sed 's/.*"//' > $(SRCNAME).lst

clean:
	rm -rf $(GEN)/* $(BIN)/* $(OBJ)/*.o $(OBJ)/*.ali b~* *.def *.lst $(LIBNAME).dll `find . -name *.class`